
import React, { useState, useEffect } from "react";
import CommonModal from '@/components/CommonModal';
import { Select, Form, message } from 'antd';
import { setAllPrinterName, getAllPrinterName } from '@/utils/authority';
import { printKxStockList, getAllPrinter } from '@/utils/print';

export const layout = {
  //发布表单排布
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
};
const { Option } = Select;
//打印状态  打印数据
let isPrinting = false;
let printArr = [];

export default ({ getPrintData,  handleOk, handleCancel }) => {

  const [form] = Form.useForm();

  //打印机列表
  const [printList, setPrintList] = useState([]);

  const [open, setOpen] = useState(false);

  useEffect(() => {
    setOpen(true);
    getAllPrinter(value => {
      setPrintList(value);
      const { kx_stock_summary_printer } = getAllPrinterName();
      console.log(getAllPrinterName(), 'cess')
      //当前系统已选择打印机回显选中
      if (kx_stock_summary_printer && value.includes(kx_stock_summary_printer)) {
        form.setFieldsValue({ printer: kx_stock_summary_printer })
      }
    })
  }, [])

  // 设置打印机名称
  const handleChangePrinterName = (kx_stock_summary_printer) => {
    setAllPrinterName({ ...getAllPrinterName(), kx_stock_summary_printer })
  }

  //单次打印
  const newPrintResult = () => {
    if (printArr[0]) {
      printKxStockList(printArr[0], (val) => {
        printArr.splice(0, 1);
        newPrintResult();
      });
    } else {
      printArr = [];
      isPrinting = false;
      setOpen(false);
      message.success(`打印成功`);
      handleOk && handleOk();
    }
  };

  //打印操作
  const handlePrint = (printerName) => {
    if(!window.LODOP) {
      message.info('请安装lodop打印组件并确保组件已开启');
      return;
    }
    const arr = getPrintData(printerName)
    if(arr.length == 0) {
      message.info('未获取到打印数据');
      return;
    }
    printArr.push(...arr);
    try {
      if (!isPrinting) {
        isPrinting = true;
        newPrintResult();
      }
      message.info('正在打印，请等待');
    } catch (err) {
      message.info('请开启打印组件');
    }
  };

  //点击确定
  const onOk = () => {
    form.validateFields().then(val => {
      handlePrint(val.printer);
    })
  }

  //点击取消
  const onCancel = () => {
    setOpen(false);
  }

  const afterClose = () => {
    handleCancel();
  }

  return (
    <CommonModal
      title='选择打印机'
      open={open}
      width='456px'
      onOk={onOk}
      okText='打印'
      minHeight={124}
      onCancel={onCancel}
      afterClose={afterClose}
    >
      <Form form={form} {...layout} name='common-printer-select'>
        <Form.Item label="打印机" name="printer" rules={[{ required: true, message: '请先选择打印机' }]}>
          <Select placeholder="请选择打印机" onChange={handleChangePrinterName} >
            {printList.map(d => <Option key={d} value={d}>{d}</Option>)}
          </Select>
        </Form.Item>
      </Form>
    </CommonModal>
  );
}
